import {DeviceEventEmitter} from 'react-native';
import Geolocation from '@react-native-community/geolocation';
import LocationServicesDialogBox from 'react-native-android-location-services-dialog-box';
import {isAndroid} from '@/constants';
import {getValue, saveValue} from './asyncStorage';

async function checkAndroidLocationProviderEnable(addlisten) {
  if (isAndroid) {
    try {
      await LocationServicesDialogBox.checkLocationServicesIsEnabled({
        message: '<h2>开启位置服务</h2>请开启位置服务以获取精准定位',
        ok: '去开启',
        cancel: '取消',
        enableHighAccuracy: false,
        showDialog: true,
        openLocationServices: true,
        preventOutSideTouch: false,
        preventBackClick: false,
        providerListener: true,
      });
    } catch (error) {
      console.log('check android location service errror', error.message);
    }
    if (addlisten) {
      DeviceEventEmitter.addListener(
        'locationProviderStatusChange',
        (lpStatusBlk) => {
          // only trigger when "providerListener" is enabled
          // {enabled: false, status: "disabled"} or {enabled: true, status: "enabled"}
          if (!lpStatusBlk.enabled) {
            saveValue('geolocation', {
              enabled: false,
            });
          }
        },
      );
    }
  }
}
export function watchGeoLocation() {
  let locationWatchId;
  async function watchLocation() {
    await checkAndroidLocationProviderEnable(true);
    locationWatchId = Geolocation.watchPosition(
      (location) => {
        saveValue('geolocation', {
          enabled: true,
          latitude: location.coords.latitude, // 纬度
          longitude: location.coords.longitude, // 经度
          altitude: location.coords.altitude, // 海拔
          heading: location.coords.heading, //朝向
        });
      },
      (err) => console.log('watch postion', err),
      {
        enableHighAccuracy: false,
        timeout: 20000,
        maximumAge: 60000,
        distanceFilter: 50,
      },
    );
  }
  watchLocation();
  return () => {
    if (locationWatchId) {
      Geolocation.clearWatch(locationWatchId);
    }
  };
}

export async function getCurrentGeoLocation() {
  //const geolocation = await getValue('geolocation');
  //if (!geolocation.enabled) {
  //  await checkAndroidLocationProviderEnable();
  //}
  await checkAndroidLocationProviderEnable();
  const postion = await new Promise((resolve, reject) => {
    Geolocation.getCurrentPosition(
      (location) => {
        resolve(location.coords);
      },
      (err) => reject(err),
      {timeout: 20000},
    );
  });
  return postion;
}
